﻿package kliment {
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.StageDisplayState;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;;
	import flash.events.KeyboardEvent;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import flash.system.System;
	import flash.ui.Keyboard;
	
	/**
     * Dispatched when complete
     */
    [Event(name = 'complete', type = 'flash.events.Event')]
	/**
	* ...
	* @author	Kliment
	* @version	1.2.11
	*/
	public class BaseApplication extends MovieClip {
		static public var ENABLE_BROWSER_HOTKEY:Boolean = true;
		static private var _instance:BaseApplication; static public function get instance():BaseApplication { return _instance; }
		
		public function BaseApplication():void {
			if (_instance) throw new Error("**Error** - singleton. Сonstructor is locked. Use instance");
			_instance = this;
			
			addEventListener(Event.ADDED_TO_STAGE, _onAddToSatage);
		}
		
		private function _onAddToSatage(event:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, _onAddToSatage);
			
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.showDefaultContextMenu = false;
			
			stage.addEventListener(KeyboardEvent.KEY_UP, _keyboardHandler);
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function _keyboardHandler(event:KeyboardEvent):void {
			if (!ENABLE_BROWSER_HOTKEY) return;
			switch(event.keyCode) {
				case 87: // w 
					if (event.ctrlKey) { // Ctrl + w 
						navigateToURL(new URLRequest('javascript:window.opener=self; window.close();')); // don't work in FireFox
						//navigateToURL(new URLRequest('javascript:self.close();'));
						//navigateToURL(new URLRequest("javascript:window.open('','_parent',''); window.close();"));
					}
				break;
				
				case Keyboard.F5: // F5 
					navigateToURL(new URLRequest('javascript:location.reload(true);'), '_self');
				break;
				
				case Keyboard.RIGHT: // → 
					if (event.altKey) // Alt + → 
						navigateToURL(new URLRequest('javascript:history.go(1);'), '_self');
				break;
				
				case Keyboard.LEFT: // ← 
					if (event.altKey) // Alt + ← 
						navigateToURL(new URLRequest('javascript:history.go(-1);'), '_self');
				break;
				
				case Keyboard.F4: // F4 
					if (event.altKey) // Alt + F4 
						navigateToURL(new URLRequest('javascript:window.close();'), '_self');
				break;
			}
		}
		
		public function get flashVars():Object {
			return stage.loaderInfo.parameters;
		}
		
		public static function get fullScreen():Boolean { return (_instance.stage.displayState == StageDisplayState.FULL_SCREEN)?true:false;}
		public static function set fullScreen(value:Boolean):void {
			_instance.stage.displayState = (value)?StageDisplayState.FULL_SCREEN:StageDisplayState.NORMAL;
		}
		
	}
}